const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
// const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

module.exports = env => {
  if(!env) {
    env = {}
  }
  let plugins = [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      template: './app/views/index.html'
    }),
    new VueLoaderPlugin(),
  ]
  if(env.production) {
    plugins.push(
      new MiniCssExtractPlugin({
        // filename: path.posix.join(__dirname, '../dist/style.css')  vue-loader css提取
        filename: 'style.css'
      }),
      // new UglifyJsPlugin({
      //   sourceMap: true
      // })  
      //生产环境js压缩
      // new webpack.DefinePlugin({
      //   'process.env': {
      //     NODE_ENV: '"production"'
      //   }
      //   // 'process.env.NODE_ENV': JSON.stringify('production')
      // })
      new webpack.optimize.UglifyJsPlugin({
        compress: {     //压缩代码
            dead_code: true,    //移除没被引用的代码
            warnings: false,     //当删除没有用处的代码时，显示警告
            loops: true //当do、while 、 for循环的判断条件可以确定是，对其进行优化
        },
        except: ['$super', '$', 'exports', 'require']    //混淆,并排除关键字
    })

    )
  }
  return {
    entry: {
      app: './app/js/main.js'
    },
    mode: 'development',
    devServer: {
      contentBase: path.join(__dirname, "dist"),
      compress: true,
      port: 9000
    },
    module: {
      rules: [{
        test: /\.html$/,
        loader: 'html-loader'
      }, {
        test: /\.vue$/,
        use: [
          'vue-loader'
        ]
      }, {
        test: /\.(scss|css)$/,
        use: [
          // process.env.NODE_ENV !== 'production'
          !env.production
            ? 'style-loader'
            : MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: { 
              modules: true
            }
          },
          {
            loader: 'px2rem-loader',
            // options here
            options: {
              remUni: 75,
              remPrecision: 8
            }
          },
          'sass-loader'
        ]
      }]
    },
    devtool: 'source-map',
    plugins,
    resolve: {
      alias: {
        'vue$': 'vue/dist/vue.esm.js'
      }
    },
    output: {
      filename: '[name].min.js',
      path: path.resolve(__dirname, 'dist')
    }
  }
}